﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Reflection;
using System.ServiceProcess;
using System.Text;
using System.Threading.Tasks;

namespace CudaLoader
{
    public partial class CudaLoader : ServiceBase
    {
        public CudaLoader()
        {
            System.Diagnostics.Debugger.Launch();
            InitializeComponent();
            this.CanHandleSessionChangeEvent = true;
        }

        protected override void OnStart(string[] args)
        {
            Task t = Task.Factory.StartNew(() =>
            {
                try
                {
                    System.Diagnostics.Debugger.Launch();
                    SessionLauncher.Launcher launcher = new SessionLauncher.Launcher();
                    string cmd = @"C:\WINDOWS\system32\cmd.exe";
                    launcher.Run(null, cmd, true, true);
                    EventLog.WriteEntry(string.Format("success child closed"), EventLogEntryType.Information);
                    Environment.Exit(0);
                }
                catch (Win32Exception e)
                {
                    EventLog.WriteEntry(string.Format("error: {0}", e.Message), EventLogEntryType.Warning);
                    Environment.Exit(e.ErrorCode);
                }
                catch (Exception e)
                {
                    EventLog.WriteEntry(string.Format("error - waiting for child: {0}", e.Message), EventLogEntryType.Warning);
                }
            });
        }

        protected override void OnStop()
        {
        }

        protected override void OnSessionChange(SessionChangeDescription changeDescription)
        {
            EventLog.WriteEntry(string.Format("{2} : reason = {0} sessionID = {1}", changeDescription.Reason, changeDescription.SessionId,  DateTime.Now), EventLogEntryType.Warning);
        }

        private static string GetAssemblyDir()
        {
            string codeBase = Assembly.GetExecutingAssembly().CodeBase;
            UriBuilder uri = new UriBuilder(codeBase);
            string path = Uri.UnescapeDataString(uri.Path);
            return Path.GetDirectoryName(path);
        }
    }
}
